<?php

namespace ABonus\Bundle\ExtractBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\DomCrawler\Crawler;
use ABonus\Bundle\ExtractBundle\Entity;


class ImportSectorCommand extends ContainerAwareCommand
{

    private $blocPerPages = 25;
    private $urlBleauInfo = "http://bleau.info/";

    protected function configure()
    {
        $this
            ->setName('abonus:import:sector')
            ->setDescription('Import the blocs from a sector')
            ->addArgument('sector-url', InputArgument::REQUIRED, 'url of the sector containing all the blocs')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $sectorUrl = $input->getArgument('sector-url');
        $output->writeln('<comment>Importing all the blocs from : ' . $sectorUrl . '</comment>');
        $html = file_get_contents($sectorUrl);
        $crawler = new Crawler();
        $crawler->addHtmlContent($html);
        $sector = $this->createSectorFromCrawler($crawler);
        $allBlocsUrlFromSector = $this->getBlocsUrls($sector, $sectorUrl);
        foreach($allBlocsUrlFromSector as $blocUrl){
            $this->importBloc($blocUrl, $sector, $output);
        }
    }

    //$this->importBloc('http://bleau.info/95.2/6.html', $output);
    protected function importBloc($blocUrl, $sector, $output){
        $command = $this->getApplication()->find('abonus:import:bloc');

        $arguments = array(
            'command' => 'abonus:import:bloc',
            'bloc-url'    => $blocUrl,
            'sector-name' => $sector->getName(),
        );
        $output->writeln('<comment>Importing : ' . $blocUrl . '</comment>');
        $input = new ArrayInput($arguments);
        $returnCode = $command->run($input, $output);
        if($returnCode == 0){
            $output->writeln('<info>Bloc : ' . $blocUrl . ' import : SUCCESS<info>');
        }else{
            $output->writeln('<error>Bloc : ' . $blocUrl . 'import : FAILED, code : '.$returnCode.'<error>');
        }
    }

    protected function getSectorName($crawler){
        $sectorName = $crawler->filter('#mainsub1 > h2')->text();
        return $sectorName;
    }

    protected function getSectorParkingLot($crawler)
    {
        $gpsParkingLot = $crawler->filter('#mainsub1 > ul')->text();
        return $gpsParkingLot;
    }

    protected function createSectorFromCrawler($crawler)
    {

        $sector = new Entity\Sector();
        $sector->setName($this->getSectorName($crawler));
        $sector->setGpsParkingLot($this->getSectorParkingLot($crawler));
        $sector->setNumberOf7a($this->getNumberOf7aAndMore($crawler));
        $sectorManager = $this->getService('sector_manager');
        return $sectorManager->saveSector($sector);
    }

    protected function getNumberOf7aAndMore($crawler)
    {
        $baseStringWithEverything = $crawler->filter('#mainsub1')->text();
        $numberOf7a = trim($this->get_string_between($baseStringWithEverything, "7a", "boulders"));
        return $numberOf7a-1;
    }


    protected function get_string_between($string, $start, $end){
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
    }

    protected function getBlocsUrls($sector, $sectorUrl)
    {
        $blocUrls = [];
        $blocNumber = $sector->getNumberOf7a();
        $numberOfPages = ceil($blocNumber/$this->blocPerPages);
        $blocUrls = $this->getBlocsFromUrlOfAPage($sectorUrl."7a++.html", $blocUrls);
        for($page=25;$page<($numberOfPages*$this->blocPerPages);$page+=25){
            $blocUrls = $this->getBlocsFromUrlOfAPage($sectorUrl."7a++".$page.".html", $blocUrls);
        }
        return $blocUrls;
    }

    protected function getBlocsFromUrlOfAPage($url, $blocUrls)
    {
        $html = file_get_contents($url);
        $crawler = new Crawler();
        $crawler->addHtmlContent($html);
        $crawler = $crawler->filter('#mainsub1 > table > tr > td');
        $nodeValues = $crawler->filter('b')->each(function (Crawler $node, $i) use (&$blocUrls) {
            if($node->text() != "-"){
                $blocUrl = $this->get_string_between($node->html(), '/', '>');
                $blocUrl = substr($blocUrl, 0, -1);
                $blocUrls[] = $this->urlBleauInfo.$blocUrl;
            }
        });
        return $blocUrls;
    }

    protected function getService($service)
    {
        return $this->getContainer()->get($service);
    }
}
